<template>
	<div class='userInfoManager-container'>
		<div class='top'>
			<div class='left'>
				<h2>个人信息</h2>
			</div>
			<div class='right'>
				<h2>基本资料</h2>
			</div>
		</div>
		<div class='bottom'>
			<div class='left'>
				<n-scrollbar trigger='hover'>
					<div class='avatar'>
						<n-avatar
							class='img' shape='square'
							fit='cover' alt='用户头像'
							:src='showUserInfo["pictureStr"] as string'>
							<template v-slot:fallback>
								<n-flex justify='center' style='width:100%;'>
									<SvgIcon icon-type='customized' icon-class='customized-tupian2'
											 height='34px' width='34px'/>
								</n-flex>
							</template>
							<template v-slot:placeholder>
								加载中......
							</template>
						</n-avatar>
					</div>
					<ul class='info-list'>
						<li>
							<span>登录账号：</span>
							{{ showUserInfo['userName'] }}
						</li>
						<li>
							<span>所在部门</span>
							<template v-for='item in showUserInfo["deptNameList"]'>
								<div class='list-item'>{{ item }}</div>
							</template>
						</li>
						<li>
							<span>👇角色列表👇</span>
						</li>
						<li>
							<template v-for='item in showUserInfo["roleNameList"]'>
								<div class='list-item'>{{ item }}</div>
							</template>
						</li>
					</ul>
				</n-scrollbar>
			</div>
			<div class='right'>
				<n-scrollbar trigger='hover'>
					<div class='form'>
						<n-form
							ref='userInfoFormRef' v-bind='formConfig'
							:model='formData' :rules='formRules' :style='{width:"70%"}'>
							<n-grid :y-gap='10' :cols='1' item-responsive>
								<n-grid-item>
									<n-form-item label='用户昵称' path='nickName'>
										<n-input
											v-model:value='formData["nickName"]'
											placeholder='请输入昵称' type='text' clearable/>
									</n-form-item>
								</n-grid-item>
								<n-grid-item>
									<n-form-item label='身份证号' path='idCard'>
										<n-input
											v-model:value='formData["idCard"]'
											placeholder='请输入身份证号' type='text' clearable/>
									</n-form-item>
								</n-grid-item>
								<n-grid-item>
									<n-form-item label='手机号码' path='phone'>
										<n-input
											v-model:value='formData["phone"]'
											placeholder='请输入手机号码' type='text' clearable/>
									</n-form-item>
								</n-grid-item>
								<n-grid-item>
									<n-form-item label='电子邮箱' path='email'>
										<n-input
											v-model:value='formData["email"]'
											placeholder='请输入电子邮箱' type='text' clearable/>
									</n-form-item>
								</n-grid-item>
								<n-grid-item>
									<n-form-item label='地址' path='address'>
										<n-input
											v-model:value='formData["address"]'
											placeholder='请输入地址' type='text' clearable/>
									</n-form-item>
								</n-grid-item>
								<n-grid-item>
									<n-form-item label='描述信息' path='remark'>
										<n-input v-model:value='formData.remark'
												 type='textarea' placeholder='请输入描述信息'
												 :autosize='{minRows:3,maxRows:3}' clearable
												 maxlength='200' show-word-count/>
									</n-form-item>
								</n-grid-item>
								<n-grid-item>
									<n-flex justify='center'>
										<n-button round strong :bordered='false'
												  type='warning' @click='submit'>
											确认修改
										</n-button>
									</n-flex>
								</n-grid-item>
							</n-grid>
						</n-form>
					</div>
				</n-scrollbar>
			</div>
		</div>
	</div>
</template>
<script lang='ts' setup>
import { defineAsyncComponent, nextTick, onMounted, reactive, ref } from 'vue';
import axios from '@/config/axios/index.ts';
import { VxeUI } from '@/config/vxe/index.ts';
import { FormProps, FormRules, FormItemRule, FormValidationError } from 'naive-ui';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import type { ShowUserInfo } from '#/src/components/page/systemManager/userInfoMaintain/ShowUserInfo.d.ts';
import type { UserInfo } from '#/src/components/page/systemManager/userInfoMaintain/UserInfo.d.ts';
const SvgIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/SvgIcon.vue'));
const userInfoFormRef = ref();
const showUserInfo = reactive<ShowUserInfo>({
	userName     : null,
	deptCodeList : null,
	deptNameList : null,
	roleCodeList : null,
	roleNameList : null,
	pictureKey   : null,
	pictureStr   : null
});
const formConfig = reactive<FormProps>({
	disabled             : false,
	inline               : false,
	labelWidth           : 'auto',
	labelAlign           : 'left',
	labelPlacement       : 'left',
	showFeedback         : true,
	showLabel            : true,
	showRequireMark      : true,
	requireMarkPlacement : 'left',
	size                 : 'medium',
	validateMessages     : undefined
});
const formData = reactive<UserInfo>({
	id       : null,
	nickName : null,
	idCard   : null,
	phone    : null,
	email    : null,
	address  : null,
	remark   : null
});
const formRules = reactive<FormRules>({
	nickName : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入昵称'
	},
	address  : {
		required : false
	},
	email    : {
		required : false,
		trigger  : ['input', 'blur'],
		validator(rule: FormItemRule, value: any) {
			return new Promise<void>((resolve, reject) => {
				// 如果没填写任何字符,那就不检测
				if (!value) {
					resolve();
				}
				const regExp = /^\w+@[a-z0-9]+\.[a-z]{2,4}$/;
				if (!regExp.test(value)) {
					reject(Error('邮箱格式不对'));
				}
				resolve();
			});
		}
	},
	phone    : {
		required : false,
		trigger  : ['input', 'blur'],
		validator(rule: FormItemRule, value: any) {
			return new Promise<void>((resolve, reject) => {
				// 没有填写,那就不管,直接通过
				if (!value) {
					resolve();
				}
				// 检查是否满足11位
				if (11 !== value.length) {
					reject(Error('长度是11个数字'));
				}
				// 没有任何问题就检测通过
				resolve();
			});
		}
	},
	idCard   : {
		required : true,
		trigger  : ['input', 'blur'],
		validator(rule: FormItemRule, value: any) {
			return new Promise<void>((resolve, reject) => {
				// 身份证是必输项,不存在则不通过
				if (!value) {
					reject(Error('请输入身份证号'));
				}
				// 新一代的身份证是18位的,位数不足则不通过
				if (18 !== value.length) {
					reject(Error('长度是18个字符'));
				}
				// 没有检测出问题则通过
				resolve();
			});
		}
	},
	remark   : {
		required : false
	}
});
const uploadFile = reactive({});
onMounted(() => {
	initData();
});
const initData = () => {
	axios<any, JsonResultProps<any>, any>({
		method : 'GET',
		url    : '/user/userInfo'
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult['status']) {
			Object.assign(showUserInfo, jsonResult['data']);
			Object.assign(formData, jsonResult['data']);
		} else {
			VxeUI.modal.message({ content : jsonResult['msg'], status : 'warning', id : 'failedMessage' });
		}
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({ content : '系统异常,请稍后再试', status : 'error', id : 'errorMessage' });
	});
};
// const upLoadAvatar = (file: unknown) => {
// 	if ((file['size'] > 1024000 * 2)) {
// 		VxeUI.modal.message({
// 			content : `${file['name']}太大`,
// 			status  : 'warning',
// 			id      : `fileSizeTooLargeMessage${file['name']}`
// 		});
// 	} else if (0 >= file['size']) {
// 		VxeUI.modal.message({
// 			content : `${file['name']}内容为空`,
// 			status  : 'warning',
// 			id      : `fileSizeIsEmptyMessage${file['name']}`
// 		});
// 	} else {
// 		/*uploadFile = {
// 		 file     : file,
// 		 fileName : file['name'],
// 		 fileSize : file['size']
// 		 };*/
// 	}
// 	const data = new FormData();
// 	data.append('file', uploadFile['file'], uploadFile['name']);
// 	axios({
// 		method  : 'POST',
// 		url     : '/fjgl/uploadFile',
// 		headers : { 'Content-Type' : 'multipart/form-data' },
// 		data    : data
// 	}).then((jsonResult: unknown) => {
// 		if (jsonResult['status']) {
// 			formData['pictureKey'] = jsonResult['data']['pictureKey'];
// 			formData['pictureStr'] = jsonResult['data']['pictureStr'];
// 		} else {
// 			VxeUI.modal.message({ content : jsonResult['msg'], status : 'warning', id : 'failedMessage' });
// 		}
// 		// uploadFile = null;
// 	}).catch((errorObj: unknown) => {
// 		console.error(errorObj);
// 		VxeUI.modal.message({ content : '系统异常,请稍后再试', status : 'error', id : 'errorMessage' });
// 		// uploadFile = null;
// 	});
// 	return false;
// };
const submit = () => {
	userInfoFormRef.value?.validate((errors?: Array<FormValidationError>): void => {
		if (errors) {
			VxeUI.modal.message({ content : '请先完善填写的内容!', status : 'warning', id : 'validateMessage' });
		} else {
			axios<any, JsonResultProps<any>, any>({
				method : 'PUT',
				url    : '/user/onlyUpdateUserInfo',
				data   : formData
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					VxeUI.modal.message({ content : jsonResult['msg'], status : 'success', id : 'successMessage' });
					nextTick(() => {
						initData();
					});
				} else {
					VxeUI.modal.message({ content : jsonResult['msg'], status : 'warning', id : 'failedMessage' });
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({ content : '系统异常,请稍后再试', status : 'error', id : 'errorMessage' });
			});
		}
	});
};
</script>
<style lang='scss' scoped>
.userInfoManager-container{
	height          :100%;
	width           :100%;
	border          :0;
	margin          :0;
	padding         :0;
	display         :flex;
	flex-direction  :column;
	flex-wrap       :nowrap;
	align-content   :center;
	justify-content :flex-start;
	align-items     :center;
	.top{
		height          :10%;
		min-height      :30px;
		max-height      :30px;
		width           :100%;
		border          :0;
		margin          :0;
		padding         :0;
		display         :flex;
		flex-direction  :row;
		flex-wrap       :nowrap;
		align-content   :center;
		justify-content :center;
		align-items     :center;
		.left{
			height          :100%;
			width           :25%;
			border          :0;
			margin          :0;
			padding         :0;
			display         :flex;
			text-align      :center;
			flex-direction  :column;
			flex-wrap       :nowrap;
			align-content   :center;
			justify-content :center;
			align-items     :center;
		}
		.right{
			height          :100%;
			width           :75%;
			border          :0;
			margin          :0;
			padding         :0;
			display         :flex;
			text-align      :center;
			flex-direction  :column;
			flex-wrap       :nowrap;
			align-content   :center;
			justify-content :center;
			align-items     :center;
		}
	}
	.bottom{
		height          :90%;
		width           :100%;
		border          :0;
		margin          :0;
		padding         :0;
		display         :flex;
		flex-direction  :row;
		flex-wrap       :nowrap;
		align-content   :center;
		justify-content :center;
		align-items     :center;
		.left{
			height          :100%;
			width           :25%;
			border          :0;
			margin          :0;
			padding         :0;
			display         :flex;
			flex-direction  :column;
			flex-wrap       :nowrap;
			align-content   :flex-start;
			justify-content :flex-start;
			align-items     :center;
			.avatar{
				height          :40%;
				width           :100%;
				border          :0;
				margin          :0;
				padding         :0;
				flex            :2;
				display         :flex;
				flex-direction  :row;
				flex-wrap       :nowrap;
				align-content   :center;
				justify-content :center;
				align-items     :center;
				.img{
					height  :95%;
					width   :95%;
					border  :0;
					margin  :0;
					padding :0;
				}
			}
			.info-list{
				height          :50%;
				width           :100%;
				border          :0;
				margin          :0;
				padding         :0;
				list-style-type :none;
				flex            :3;
				display         :flex;
				flex-direction  :column;
				flex-wrap       :nowrap;
				align-content   :center;
				justify-content :flex-start;
				align-items     :stretch;
				li{
					font-size   :1.25rem;
					font-weight :400;
					text-align  :center;
				}
			}
		}
		.right{
			height  :100%;
			width   :75%;
			border  :0;
			margin  :0;
			padding :0;
			.form{
				width         :100%;
				border        :0;
				margin        :0;
				padding       :0;
				display       :flex;
				flex-flow     :column nowrap;
				place-content :center center;
				place-items   :center center;
				place-self    :center center;
			}
		}
	}
}
</style>